package com.gzw.dms.utils;

import android.graphics.Bitmap;
import android.os.Handler;

import com.gzw.dms.MyApplication;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.message.BasicNameValuePair;
import cz.msebera.android.httpclient.util.EntityUtils;

public class FileUtil {
    private static FileUtil instance;
    private String isUpLoad="0";
    public static FileUtil getInstance() {
        if (instance == null) {
            instance = new FileUtil();
        }
        return instance;
    }
    public void uploadFile(final Bitmap mBitmap, final String newFileName ,final  String fileRoot) {
        String imgString = ToolFor9Ge.getBase64FromBitmap(mBitmap,100);
        uploadFile(imgString, newFileName, fileRoot);
    }
    private void uploadFile(final String imgString, final String newFileName,final  String fileRoot) {
        new Thread() {
            @Override
            public void run() {
                udload(imgString, newFileName,fileRoot);
            }
        }.start();
    }
    public void udload(String imgString, String newFileName,String fileRoot) {
        isUpLoad="1";
        String json="imgString="+imgString+"&newFileName="+newFileName+"&fileRoot="+fileRoot;
        final String result=HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("getUploadImage"),json);

        new Handler(MyApplication.getmContext().getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (result.equals("")) {
                    T.showShort(MyApplication.getmContext(), "连接服务器异常");
                    isUpLoad = "0";
                } else {

                    if (result.indexOf("errorMsg") > 0) {
                        String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                        T.showShort(MyApplication.getmContext(), errorMsg);
                        isUpLoad = "0";
                    } else {
                        String successMsg = JsonUtil.getMsg(result, "successMsg");
                        T.showShort(MyApplication.getmContext(), JsonUtil.getMsg(result, "successMsg"));


                        if (JsonUtil.getMsg(result, "successMsg").equals("成功")) {
                            isUpLoad = "2";
                        } else {
                            isUpLoad = "0";
                        }
                        L.i("----------udload----------HttpUtils.doPost", result);
                    }
                }
            }
        });
    }

    public String isUpload(){
        return String.valueOf(isUpLoad);
    }
    public void noUpload(){
        isUpLoad = "0";
    }
    // 上传
    public void upload(Bitmap upbitmap,String newFileName) {
        String json="imgString="+upbitmap+"&newFileName="+newFileName+"";
        String HOST =UrlUtils.getInstance().getJavaUrl("getUploadImage")+"json="+json;

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
        upbitmap.compress(Bitmap.CompressFormat.JPEG, 60, stream);
        byte[] b = stream.toByteArray();
        // 将图片流以字符串形式存储下来
        String file = new String(Base64Coder.encodeLines(b));
        HttpClient client = new DefaultHttpClient();
        // 设置上传参数
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("file", file));
        HttpPost post = new HttpPost(HOST);
        UrlEncodedFormEntity entity;
        try {
            entity = new UrlEncodedFormEntity(formparams, "UTF-8");
            post.addHeader("Accept",
                    "text/javascript, text/html, application/xml, text/xml");
            post.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
            post.addHeader("Accept-Encoding", "gzip,deflate,sdch");
            post.addHeader("Connection", "Keep-Alive");
            post.addHeader("Cache-Control", "no-cache");
            post.addHeader("Content-Type", "application/x-www-form-urlencoded");
            post.setEntity(entity);
            HttpResponse response = client.execute(post);
            System.out.println(response.getStatusLine().getStatusCode());
            HttpEntity e = response.getEntity();
            System.out.println(EntityUtils.toString(e));
            if (200 == response.getStatusLine().getStatusCode()) {
                System.out.println("上传完成");
            } else {
                System.out.println("上传失败");
            }
            client.getConnectionManager().shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /* 上传文件至Server的方法 */
    public void uploadPhoto(String imgString, String newFileName)
    {
        final String actionUrl=UrlUtils.getInstance().getJavaUrl("getUploadImage");
        String end ="\r\n";
        String twoHyphens ="--";
        String boundary ="*****";
        try
        {
            URL url =new URL(actionUrl);
            HttpURLConnection con=(HttpURLConnection)url.openConnection();
          /* 允许Input、Output，不使用Cache */
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
          /* 设置传送的method=POST */
            con.setRequestMethod("POST");
          /* setRequestProperty */
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary="+boundary);
          /* 设置DataOutputStream */
            DataOutputStream ds =
                    new DataOutputStream(con.getOutputStream());
            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; "+
                    "name=\"file1\";filename=\""+
                    imgString +"\""+ end);
            ds.writeBytes(end);
          /* 取得文件的FileInputStream */
            FileInputStream fStream =new FileInputStream(newFileName);
          /* 设置每次写入1024bytes */
            int bufferSize =1024;
            byte[] buffer =new byte[bufferSize];
            int length =-1;
          /* 从文件读取数据至缓冲区 */
            while((length = fStream.read(buffer)) !=-1)
            {
            /* 将资料写入DataOutputStream中 */
                ds.write(buffer, 0, length);
            }
            ds.writeBytes(end);
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
          /* close streams */
            fStream.close();
            ds.flush();
          /* 取得Response内容 */
            InputStream is = con.getInputStream();
            int ch;
            StringBuffer b =new StringBuffer();
            while( ( ch = is.read() ) !=-1 )
            {
                b.append( (char)ch );
            }
          /* 将Response显示于Dialog */
//            showDialog("上传成功"+b.toString().trim());
          /* 关闭DataOutputStream */
            ds.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
//            showDialog("上传失败" + e);
        }
    }

}